<?php
namespace app\user\controller;
use think\Controller;
use think\facade\Request;
use think\captcha\Captcha;
class Regmin extends Controller{
    protected $sys;
    public function initialize(){
        if (!session('user.id') && session('user.level')!=1) {
            $this->redirect('index/index');
        }
        $this->sys = cache('System');
        $this->assign('sys',$this->sys);
    } 
    public function reg(){
        if(Request::isAjax()) {
            $data = input('post.'); 
            $request = Request::instance();  
            if($this->sys['code']=='open') {
                $code = $data['vercode'];
                if (!$this->check($code)) return array('code' => 0, 'msg' => '验证码错误');
            }
            $is_validated = 0 ; 
            if(is_mobile_phone($data['mobile'])){
                $is_validated = 1;
                $data['mobile_validated'] = 1; 
                if(get_user_info($data['mobile'],2)) return array('code'=>-1,'msg'=>'手机账号已存在');
            }
            if(is_email($data['email'])){
                $is_validated_e = 1; 
                if(get_user_info($data['email'],1)) return array('code'=>-1,'msg'=>'邮箱已存在');
            }
            if($is_validated != 1) return array('code'=>0,'msg'=>'请用手机号注册');
            if($is_validated_e != 1) return array('code'=>0,'msg'=>'请输入正确的邮箱');
            if(!$data['username'] || !$data['password']) return array('code'=>-1,'msg'=>'请输入姓名或密码');
            //验证两次密码是否匹配
            if($data['password'] != $data['password2']) return array('code'=>-1,'msg'=>'两次输入密码不一致');
            unset($data['password2']);
            unset($data['vercode']);
            //验证是否存在用户名 
            $data['password'] = md5($data['password']);
            $data['reg_time'] = time();
            $data['last_ip'] = $request->ip();
            $data['appid'] = rand_string(8,1);
            $data['appkey'] = rand_string(24,5);
            $id = db('users')->insertGetId($data);
            if($id === false){
                return array('code'=>-1,'msg'=>'开通失败');
            }else{ 
                return array('code'=>1,'msg'=>'开通成功');
            }
        }else { 
            $this->assign('agentid',input('agentid'));
            $this->assign('title', '自助开通');
            return $this->fetch('/login/reg');
        }
    } 
    // 图形验证码
    public function verify(){
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    25,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'bg'          =>    [255,255,255],
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    // 检测验证码
    public function check($code){
        return captcha_check($code);
    }
}